import Order, { IOrder } from "../../models/Order";
import Product from "../../models/Product";
import BlindBox from "../../models/BlindBox";
import Member from "../../models/Member";
import moment from "moment";
import _ from "lodash";
import mongoose from "mongoose";
import AlipaySdk from "alipay-sdk";
import { handleLottery } from '../OrderController'

const alipaySdk = new AlipaySdk({
    appId: "2021004130661796",
    signType: "RSA2",
    // gateway: "https://openapi.alipaydev.com/gateway.do",
    privateKey:
        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDQ4TEioaEwmgc3UgRxzBvtqzDKsU8yH+wWSLMzoalNXYHuMa0aZNwWBTYjbuizSWgrzdREnUzevgp5fHFLgVJi9xu3geNm0R0XKJ+wBJ5vJFTfEIytBElvTBa4MjYLTgFK/OoR0uW30SViGkbrGnd3N/2vFVNqJiLv9aTg6VJPaIp5ld7HkoPcyDZHRdOBZyXLnAbQzYvK6oHolZMbInsWNGGLp9AdyZEApVEYroCAyWUhe4lq+R1lfSGoIlVCb+YhR1qjaPlVA5/zF3Jlb2vg+MlZnncJQWMKn9ZvGWuFSCilLUFf4R9X7ySgSXuo6DDF+DUz8ScQbXAxk4C8tzv1AgMBAAECggEAbgqU9iesYYxjzNMaoFDlTbpoRABRNpj2qW63abX7GVTvxGrLRSJph/hK4zPkx78ecCVJdLRh8N6xafsTPLHuk1CXe3+kK2BzMOYn6nUkemzrgXCYi/W8MjQlq/hX3HDF4ZmIPseaWdKHHT22qtkQovAOZ5SWk09wDHae3BZPVKFMpyJwS/NGh8TiTLNLXGOq1PN6eyEFqyBxB5IJ4ro53RIJhUmjpoOLLBxdCjFTiP00tUY2S00IKrxa83hItRqM7PYavxUdy2SS97VAil4KOqU59BAMbEk7jNFhhYJ+VQzU8f86tVzOgzqZTRusKPvrDcHEtnYjdsM/hghpuuAOKQKBgQDw/b6ZOgnf9yyXJ3bHOCEaXtH9g2kCp5oUYxxFkH4FeJn5kP+L+w3usqauIOgypcshEARsLkj/BAFgRjtWUeV2iAJj9XHN12zBC/920gocy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JVQm/mIUdao2j5VQOf8xdyZW9r4PjJWZ53CUFjCp/WbxlrhUgopS1BX+EfV+8koEl7qOgwxfg1M/EnEG1wMZOAvLc79QIDAQAB",
});

const payOrderForBlindBox = async (req: any, res: any) => {
    try {
        console.log("支付参数：", req.body);
        const { orderId, payType, price, productName, quantity, remark } = req.body;

        // 1. 查找订单并验证有效性
        const order = await Order.findById(orderId);
        console.log("查找订单并验证有效性:", order);
        if (!order) {
            return res.status(500).json({
                status: "false",
                message: "订单不存在",
                data: {
                    orderId,
                },
            });
        }

        const currentTime = moment(); // 当前时间
        const orderTime = moment(order.createdAt); // 订单创建时间
        const timeDifference = currentTime.diff(orderTime, "minutes"); // 计算时间差，单位分钟

        if (timeDifference > 30) {
            return res.status(500).json({
                status: "false",
                message: "订单已失效",
                data: {
                    orderId,
                },
            });
        }

        // 2. 查找盲盒并验证库存
        const blindBox = await BlindBox.findById(order.product.goodsId);
        console.log("查找盲盒并验证库存:", blindBox);
        if (!blindBox) {
            return res.status(500).json({
                status: "false",
                message: "盲盒商品不存在",
                data: {
                    orderId,
                },
            });
        }

        if (blindBox.stock - order.quantity < 0) {
            return res.status(500).json({
                status: "false",
                message: "盲盒库存不足",
                data: {
                    orderId,
                },
            });
        }


        // 3. 查找用户
        const member = await Member.findById(order.user);
        if (!member) {
            return res.status(500).json({
                status: "false",
                message: "用户不存在",
                data: {
                    orderId,
                },
            });
        }



        order.productType = 'blind-box'
        // 4. 判断支付类型进行支付
        if (payType === 'draws') {
            if ((member.draws || 0) < order.totalAmount) {
                return res.status(500).json({
                    status: "false",
                    message: "次数不足，无法抽奖！",
                    data: {
                        orderId,
                    },
                });
            }
            member.draws -= order.totalAmount
            blindBox.stock -= order.quantity
            order.status = "finished"
            const { lotteryResults, hasWonAnyPrize } = await handleLottery(orderId)
            order.remark = JSON.stringify(lotteryResults);
            order.payMethod = payType

            await member.save();
            await blindBox.save();
            await order.save();

            res.json({
                status: "ok",
                message: "抽奖完成！",
                data: {
                    orderId,
                    lotteryResults,
                    reward: hasWonAnyPrize,
                },
            });
        }
        // if (payType === "balance") {

        //     if ((member.balance || 0) < order.totalAmount) {
        //         return res.status(500).json({
        //             status: "false",
        //             message: "余额不足，请先充值",
        //             data: {
        //                 orderId,
        //             },
        //         });
        //     }

        //     // 使用用户余额支付、盲盒库存、订单状态
        //     // @ts-ignore
        //     member.balance -= order.totalAmount;
        //     blindBox.stock -= order.quantity;
        //     order.status = "finished";
        //     const { lotteryResults, hasWonAnyPrize } = await handleLottery(orderId)
        //     order.remark = JSON.stringify(lotteryResults);
        //     order.payMethod = payType

        //     // 保存更新后的数据
        //     await member.save();
        //     await blindBox.save();
        //     await order.save();

        //     res.json({
        //         status: "ok",
        //         message: "支付成功！",
        //         data: {
        //             orderId,
        //             lotteryResults,
        //             reward: hasWonAnyPrize,
        //         },
        //     });
        // } else if (payType === "alipay") {
        //     const bizContent = {
        //         out_trade_no: orderId,
        //         total_amount: price,
        //         subject: productName,
        //         product_code: "QUICK_WAP_WAY",
        //         // product_code: "FAST_INSTANT_TRADE_PAY",
        //     }

        //     console.log('进行支付宝支付===========', bizContent)
        //     const result = await alipaySdk.pageExec("alipay.trade.wap.pay", {
        //         method: 'POST',
        //         bizContent,
        //         returnUrl: `http://www.channing-mall.cn/order/payResult?orderId=${orderId}&payResult=success`,
        //         notifyUrl: `http://www.channing-mall.cn/order/payResult?orderId=${orderId}&payResult=success`
        //     });


        //     if (result) {
        //         // 保存更新后的数据
        //         //给用户积分
        //         member.balance = Number(member.balance) + Math.floor(price / 10)
        //         await member.save();
        //         await blindBox.save();
        //         order.payMethod = payType
        //         await order.save();

        //         console.log('返回 result:', result)

        //         res.json({
        //             status: "ok",
        //             message: "支付成功！",
        //             data: {
        //                 url: result,
        //             },
        //         });
        //     }
        // } else if (payType === "wechat-pay") {
        //     order.payMethod = payType
        // }

        // res.status(500).json({
        //     status: "false",
        //     message: "支付失败！",
        //     data: null,
        // });
    } catch (error: any) {
        res.status(500).json({
            status: "false",
            message: "支付失败！",
            data: error.message,
        });
    }
};

export default payOrderForBlindBox